<?php
$case=json_decode(file_get_contents("data/case.json"),true);
$db=json_decode(file_get_contents("data/db.json"),true);
$interface=json_decode(file_get_contents("data/interface.json"),true);
$info=json_decode(file_get_contents("data/info.json"),true);

if(!is_array($case)){
    echo 'data/case.json文件格式错误';
}
if(!is_array($db)){
    echo 'data/db.json文件格式错误';
}
if(!is_array($interface)){
    echo 'data/interface.json文件格式错误';
}
if(!is_array($info)){
    echo 'data/info.json文件格式错误';
}
?>
<?php
//* POST处理
if($_SERVER["REQUEST_METHOD"]=="POST"){
    // echo "{\"res\":\"NG\",\"message\":\"失败\"}";
    if($_POST["do"]=="db"){
        try{
            $dbl=new PDO("mysql:host=".$_POST["host"].";dbname=".$_POST["dbname"],$_POST["user"],$_POST["password"]);
        } catch(Exception $e){
            echo '{"res":"NG","message":"操作失敗:'.$e->getMessage().'"}';
            exit;
        }
        try{
            $sqlfile='';
            foreach ($db as $row) {
                $sql="drop table if exists ".$row["table"].";";
                $dbl->exec($sql);
                $sql="create table ".$row["table"]."(";
                foreach ($row["column"] as $field) {
                    if(strpos($field["index"],"primary")!==false){
                        $sql.=$field["field"]." ".$field["type"]." ".$field["index"].",";
                        continue;
                    }
                    $sql.=$field["field"]." ".$field["type"].",".(strpos($field["index"],"index")!==false?($field["index"]." idx_".$field["field"]."(".$field["field"]."),"):"");
                }
                $sql=trim($sql,",").")charset=utf8mb4;";
                $sqlfile.=$sql."\n";

                $dbl->exec($sql);
            }
            file_put_contents("data/db.sql",$sqlfile);

            echo '{"res":"OK"}';
            exit;
        }catch(Exception $e){
            echo '{"res":"NG","message":"操作失敗:'.$e->getMessage().'"}';
            exit;
        }
    }
    if($_POST["do"]=="interface"){
        foreach ($interface as $itf) {
            $sub=explode("=",$itf["url"]);
            if(count($sub)!=2){
                echo '{"res":"NG","message":"'.$itf["name"].'的接口URL定义错误,不是p=*格式"}';
                exit;
            }
            $c=explode("_",$sub[1]);
            if(count($c)!=2){
                echo '{"res":"NG","message":"'.$itf["name"].'的接口URL定义错误,不是class_func格式"}';
                exit;
            }
            if(!is_dir("../validater")){
                mkdir("../validater",0777);
            }
            $filename="../validater/".strtolower($itf["method"])."_".$sub[1].".php";
            $txt="<?php\n";
            foreach ($itf["request"] as $res) {
                //是否定义
                $txt.="if(!isset(\$_".strtoupper($itf["method"])."[\"".str_replace("[]","",$res["key"])."\"])){\n";
                $txt.="\techo '{\"res\":\"NG\",\"message\":\"".$res["key"]."没有定义\"}';\n";
                $txt.="\texit;\n";
                $txt.="}\n";

                if(strpos($res["key"],"[]")!==false){
                    //数组处理
                    $key=str_replace("[]","",$res["key"]);
                    $txt.="foreach(\$_".strtoupper($itf["method"])."[\"".$res["key"]."\"] as \$key){\n";
                    $txt.="\tif(!preg_match(\"/".$res["regex"]."/\",\$key)){\n";
                    $txt.="\t\techo '{\"res\":\"NG\",\"message\":\"".$res["name"]."的格式不符合规定\"}';\n";
                    $txt.="\t\texit;\n";
                    $txt.="\t}\n";
                    $txt.="}\n";
                }else{
                    $txt.="if(!preg_match(\"/".$res["regex"]."/\",\$_".strtoupper($itf["method"])."[\"".$res["key"]."\"])){\n";
                    $txt.="\techo '{\"res\":\"NG\",\"message\":\"".$res["name"]."的格式不符合规定\"}';\n";
                    $txt.="\texit;\n";
                    $txt.="}\n";
                }
            }
            $txt.="?>";
            file_put_contents($filename,$txt);
        }
        echo '{"res":"OK"}';
        exit;
    }
    if($_POST["do"]=="class"){
        $class=[];
        foreach ($interface as $itf) {
            $sub=explode("=",$itf["url"]);
            if(count($sub)!=2){
                echo '{"res":"NG","message":"'.$itf["name"].'的接口URL定义错误,不是p=*格式"}';
                exit;
            }
            $c=explode("_",$sub[1]);
            if(count($c)!=2){
                echo '{"res":"NG","message":"'.$itf["name"].'的接口URL定义错误,不是class_func格式"}';
                exit;
            }
            if(isset($class[$c[0]])){
                array_push($class[$c[0]],[
                    "func"=>$c[1],
                    "method"=>strtolower($itf["method"]),
                    "name"=>strtolower($itf["name"])
                ]);
            }else{
                $class[$c[0]]=[[
                    "func"=>$c[1],
                    "method"=>strtolower($itf["method"]),
                    "name"=>strtolower($itf["name"])
                ]];
            }
        }
        // print_r($class);
        if(!is_dir("../controller")){
            mkdir("../controller",0777);
        }
        foreach($class as $c=>$funcs){
            $filename="../controller/".$c.".php";
            if(is_file($filename)){
                continue;
            }
            $txt="<?php\n";
            $txt.="class {$c}{\n";
            foreach ($funcs as $func) {
                $txt.="\t//* ".$func["name"]."\n";
                $txt.="\t//* {$c}_".$func["func"]."\n";
                $txt.="\tpublic static function ".$func["method"]."_".$func["func"]."(){\n";
                $txt.="\t}\n";
            }
            $txt.="}\n";
            $txt.="?>";
            
            file_put_contents($filename,$txt);
        }
        echo '{"res":"OK"}';
        exit;
    }
    echo '{"res":"NG","message":"操作失敗"}';
    exit;
}
?>
<?php
//* case
$case_html="<div class='page'><h1>[需求清单]".$info["system"]."</h1>";
$case_html.="<table>";
$case_html.="<tr>";
$case_html.="<th>序号</th>";
$case_html.="<th>需求主题</th>";
$case_html.="<th>需求描述</th>";
$case_html.="<th>功能需求</th>";
$case_html.="<th>非功能需求</th>";
$case_html.="<th>输入数据</th>";
$case_html.="<th>输出数据</th>";
$case_html.="</tr>";
foreach ($case as $key => $item) {
    $case_html.="<tr>";
    $case_html.="<td>".($key+1)."</td>";
    $case_html.="<td>".str_replace("\n","<br>",$item["title"])."</td>";
    $case_html.="<td align='left'>".str_replace("\n","<br>",$item["desc"])."</td>";
    $case_html.="<td align='left'>".str_replace("\n","<br>",$item["function"])."</td>";
    $case_html.="<td align='left'>".str_replace("\n","<br>",$item["nofunction"])."</td>";
    $case_html.="<td align='left'>".str_replace("\n","<br>",$item["input"])."</td>";
    $case_html.="<td align='left'>".str_replace("\n","<br>",$item["output"])."</td>";
    $case_html.="</tr>";
}
$case_html.="</table></div>";

//* db
$db_html="<div class='page'><h1>[数据库设计]".$info["system"]."</h1>";
foreach ($db as $key => $table) {
    $db_html.="<table>";
    $db_html.="<caption>".($key+1).".表名称：".$table["table"]."</caption>";
    $db_html.="<tr>";
    $db_html.="<th>字段</th>";
    $db_html.="<th>数据类型</th>";
    $db_html.="<th>索引</th>";
    $db_html.="</tr>";
    foreach($table["column"] as $column){
        $db_html.="<tr>";
        $db_html.="<td>".$column["field"]."</td>";
        $db_html.="<td>".$column["type"]."</td>";
        $db_html.="<td>".$column["index"]."</td>";
        $db_html.="</tr>";
    }
    $db_html.="</table>";
}
$db_html.="</div>";

//* interface
$interface_html="<div class='page'><h1>[接口设计]".$info["system"]."</h1>";
foreach ($interface as $key => $itf) {
    $interface_html.="<table>";
    $interface_html.="<caption>".($key+1).".接口名称：".$itf["name"]."</caption>";
    $interface_html.="<tr>";
    $interface_html.="<th width='30%'>URL</th>";
    $interface_html.="<td align='left'>".$info["url"].$itf["url"]."</td>";
    $interface_html.="</tr>";
    $interface_html.="<tr>";
    $interface_html.="<th width='30%'>METHOD</th>";
    $interface_html.="<td align='left'>".$itf["method"]."</td>";
    $interface_html.="</tr>";
    $interface_html.="<tr>";
    $interface_html.="<th width='30%'>REQUEST</th>";
    $interface_html.="<td align='left'>";
    $interface_html.="<table class='tbl'>";
    $interface_html.="<tr>";
    $interface_html.="<th>参数名</th>";
    $interface_html.="<th>描述</th>";
    $interface_html.="<th>类型</th>";
    $interface_html.="<th>正则约束</th>";
    $interface_html.="</tr>";
    foreach ($itf["request"] as $req) {
        $interface_html.="<tr>";
        $interface_html.="<td>".$req["key"]."</td>";
        $interface_html.="<td>".$req["name"]."</td>";
        $interface_html.="<td>".$req["type"]."</td>";
        $interface_html.="<td>".$req["regex"]."</td>";
        $interface_html.="</tr>";
        
    }
    $interface_html.="</table>";
    $interface_html.="</td>";
    $interface_html.="</tr>";
    $interface_html.="<tr>";
    $interface_html.="<th width='30%'>RESPONSE</th>";
    $interface_html.="<td align='left'>";
    $interface_html.="<table class='tbl'>";
    $interface_html.="<tr>";
    $interface_html.="<th>参数名</th>";
    $interface_html.="<th>描述</th>";
    $interface_html.="<th>类型</th>";
    $interface_html.="<th>正则约束</th>";
    $interface_html.="</tr>";
    foreach ($itf["response"] as $res) {
        $interface_html.="<tr>";
        $interface_html.="<td>".$res["key"]."</td>";
        $interface_html.="<td>".$res["name"]."</td>";
        $interface_html.="<td>".$res["type"]."</td>";
        $interface_html.="<td>".$res["regex"]."</td>";
        $interface_html.="</tr>";
        
    }
    $interface_html.="</table>";
    $interface_html.="</tr>";
    $interface_html.="</table>";
}
$interface_html.="</div>";
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>[文档]<?php echo $info["system"];?></title>
    <style>
        body{padding:0; margin:0; border:0;}
        .bt{
            width:100%;
            line-height:40px;
            text-align:center;
            cursor: pointer;
            color:#666666;
        }
        .bt:hover{
            color:blue;
        }
        #fd{
            flex:1;
            min-height:100vh;
            overflow:auto;
        }
        .page{
            width:1000px;
            margin:0 auto;
            background-color:white;
            padding:20px;
            border-shadow:0 0 5px silver;
        }
        h1{
            text-align:center;
        }
        table{
            font-size:12px;
            border-spacing:0;
            width:100%;
            table-layout:fixed;
            text-align:center;
            margin-top:20px;
        }
        caption{
            text-align:left;
            padding:10px;
            border:solid 1px silver;
            font-size:16px;
            font-weight:bold;
        }
        th{
            padding:5px;
            border:solid 1px silver;
            background-color:#f2f2f2;
        }
        td{
            padding:5px;
            border:solid 1px silver;
        }
        .tbl{
            margin:0;
        }
        .bts{
            position:fixed;
            width:19%;
            height:40px;
            left:0;
            bottom:0;
            display:flex;
            margin:10px 0.5%;
        }
        .bts button{
            border:0;
            flex:1;
            color:#666666;
            cursor: pointer;
            border:solid 1px #f2f2f2;
        }
        .bts button:hover{
            color:black;
            font-weight:bold;
            background-color:white;
        }
        dialog{
            position:fixed; top:50%; left:50%;
            width:400px; height:300px;
            margin-left:-200px; margin-top:-150px;
            border:0;
            box-shadow:0 0 5px silver;
            padding:0;
        }
        dialog .title{
            text-align:center;
            line-height:50px;
            font-size:16px;
            font-weight:bold;
        }
        dialog .line{
            height:30px;
            padding:10px 20px;
            display:flex;
        }
        dialog .line label{
            width:80px;
            line-height:30px;
            color:#666666;
        }
        dialog .line input{
            flex:1;
        }
        dialog .menubts{
            margin:10px 0 0 0;
            height:30px;
            text-align:center;
        }
        dialog .menubts button{
            margin:0 5px;
            height:30px;
            padding:0 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div style="width:100%; height:100vh; background-color:#f2f2f2; display:flex;">
        <div class="left" style="width:20%; height:100vh; background-color:white; box-shadow:0 0 5px silver;">
            <h2 style="text-align:center;"><?php echo $info["system"];?></h2>
            <h3 style="text-align:center; color:#666666;">【系统文档】</h3>
            <div class="bt" onclick="ShowCase()">需求清单</div>
            <div class="bt" onclick="ShowDB()">数据设计</div>
            <div class="bt" onclick="ShowInterface()">接口设计</div>
        </div>
        <div id="fd"></div>
    </div>
    <div class="bts">
        <button onclick="pageprint()">打印</button>
        <button onclick="writeDB()">写入DB</button>
        <button onclick="writeInterface()">写入验证</button>
        <button onclick="writeClass()">写入方法</button>
    </div>
    <dialog></dialog>
</body>
<script>
    window.onload=function(){
        ShowCase();
    }
    function ShowCase(){
        var fd=document.querySelector("#fd");
        fd.innerHTML="<?php echo $case_html;?>";
    }
    function ShowDB(){
        var fd=document.querySelector("#fd");
        fd.innerHTML="<?php echo $db_html;?>";
    }
    function ShowInterface(){
        var fd=document.querySelector("#fd");
        fd.innerHTML="<?php echo $interface_html;?>";
    }
    function pageprint(){
        window.print();
    }
    window.onbeforeprint = function() {
        document.querySelector(".page").style.width="800px";
        document.body.innerHTML=document.querySelector(".page").outerHTML;
    };
    window.onafterprint = function() {
        location.href="index.php";
    };
    function writeDB(){
        ShowDB();
        var html="";
        html+="<div class='title'>写入DB</div>";
        html+="<div class='line'>";
        html+="<label>主机:</label>";
        html+="<input type='text' id='host'>";
        html+="</div>";
        html+="<div class='line'>";
        html+="<label>实例:</label>";
        html+="<input type='text' id='dbname'>";
        html+="</div>";
        html+="<div class='line'>";
        html+="<label>用户:</label>";
        html+="<input type='text' id='user'>";
        html+="</div>";
        html+="<div class='line'>";
        html+="<label>密码:</label>";
        html+="<input type='password' id='password'>";
        html+="</div>";
        html+="<div class='menubts'>";
        html+="<button onclick='heanderWirteDB()'>写入</button>";
        html+="<button onclick='hideDialog()'>取消</button>";
        html+="</div>";
        document.querySelector("dialog").innerHTML=html;
        document.querySelector("dialog").showModal();
    }
    function hideDialog(){
        document.querySelector("dialog").close();
    }
    function heanderWirteDB(){
        console.log("writedb");
        var postData=new FormData();
        postData.append("do","db");
        postData.append("host",document.querySelector("#host").value);
        postData.append("dbname",document.querySelector("#dbname").value);
        postData.append("user",document.querySelector("#user").value);
        postData.append("password",document.querySelector("#password").value);
        fetch('index.php', {
            method: 'POST',
            body:postData,
            })
        .then(response => response.json())
        .then(data => {
            if(data.res=="OK"){
                document.querySelector("dialog").innerHTML="<h1>写入DB成功!</h1><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }else{
                document.querySelector("dialog").innerHTML="<p style='color:red; text-align:center;'>"+data.message+"</p><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }
        })
        .catch(error => console.error('Error:', error));
    }
    function writeInterface(){
        ShowInterface();
        var postData=new FormData();
        postData.append("do","interface");
        fetch('index.php', {
            method: 'POST',
            body:postData,
            })
        .then(response => response.json())
        .then(data => {
            document.querySelector("dialog").showModal();
            if(data.res=="OK"){
                document.querySelector("dialog").innerHTML="<h1>写入验证成功!</h1><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }else{
                document.querySelector("dialog").innerHTML="<p style='color:red; text-align:center;'>"+data.message+"</p><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }
        })
        .catch(error => console.error('Error:', error));
    }
    function writeClass(){
        ShowInterface();
        var postData=new FormData();
        postData.append("do","class");
        fetch('index.php', {
            method: 'POST',
            body:postData,
            })
        .then(response => response.json())
        .then(data => {
            document.querySelector("dialog").showModal();
            if(data.res=="OK"){
                document.querySelector("dialog").innerHTML="<h1>写入方法成功!</h1><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }else{
                document.querySelector("dialog").innerHTML="<p style='color:red; text-align:center;'>"+data.message+"</p><div class='menubts'><button onclick='hideDialog()'>关闭</button></div>";
            }
        })
        .catch(error => console.error('Error:', error));
    }
</script>
</html>